package org.dromara.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.dromara.admin.domain.Company;
import org.dromara.admin.domain.model.UserPasswordBo;
import org.dromara.admin.domain.vo.CompanyVo;
import org.dromara.admin.enums.GeneralEnum;
import org.dromara.admin.service.ICompanyService;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.bo.SysUserBo;
import org.dromara.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.dromara.admin.domain.bo.EmployeeBo;
import org.dromara.admin.domain.vo.EmployeeVo;
import org.dromara.admin.domain.Employee;
import org.dromara.admin.mapper.EmployeeMapper;
import org.dromara.admin.service.IEmployeeService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 员工信息Service业务层处理
 *
 * @author Lion Li
 * @date 2025-10-10
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class EmployeeServiceImpl implements IEmployeeService {

    private final EmployeeMapper baseMapper;
    @Lazy
    @Autowired
    ISysUserService sysUserService;
    @Lazy
    @Autowired
    ICompanyService companyService;
    @Lazy
    @Autowired
    ISysUserService userService;

    /**
     * 查询员工信息
     *
     * @param id 主键
     * @return 员工信息
     */
    @Override
    public EmployeeVo queryById(Long id) {
        // 使用MPJBaseMapper进行联表查询公司主体信息Company
        MPJLambdaWrapper<Employee> wrapper = new MPJLambdaWrapper<Employee>()
            .selectAll(Employee.class)//查询Employee表全部字段
            .selectAssociation(Company.class, EmployeeVo::getCompany)
            .leftJoin(Company.class, Company::getId, Employee::getCompanyId)
            .eq(Employee::getId, id);
        EmployeeVo employeeVo = baseMapper.selectJoinOne(EmployeeVo.class, wrapper);
        if (BeanUtil.isEmpty(employeeVo)) {
            throw new ServiceException("用户信息不存在！");
        }
        return employeeVo;
    }

    /**
     * 分页查询员工信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 员工信息分页列表
     */
    @Override
    public TableDataInfo<EmployeeVo> queryPageList(EmployeeBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Employee> lqw = buildQueryWrapper(bo);
        Page<EmployeeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 分页查询当前登录用户的员工信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 员工信息分页列表
     */
    @Override
    public TableDataInfo<EmployeeVo> queryPageMyList(EmployeeBo bo, PageQuery pageQuery) {
        EmployeeVo employeeVo = this.queryById(bo.getId());

        Long companyId = employeeVo.getCompanyId();
        if (companyId == null) {
            throw new ServiceException("用户未注册公司主体信息！");
        }
        bo.setCompanyId(companyId);
        LambdaQueryWrapper<Employee> lqw = buildQueryWrapper(bo);
        Page<EmployeeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的员工信息列表
     *
     * @param bo 查询条件
     * @return 员工信息列表
     */
    @Override
    public List<EmployeeVo> queryList(EmployeeBo bo) {
        LambdaQueryWrapper<Employee> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Employee> buildQueryWrapper(EmployeeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Employee> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(Employee::getCreateTime);
        lqw.eq(bo.getCompanyId() != null, Employee::getCompanyId, bo.getCompanyId());
        lqw.like(StringUtils.isNotBlank(bo.getPhone()), Employee::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getPassword()), Employee::getPassword, bo.getPassword());
        lqw.like(StringUtils.isNotBlank(bo.getRealName()), Employee::getRealName, bo.getRealName());
        lqw.eq(bo.getRole() != null, Employee::getRole, bo.getRole());
        lqw.eq(bo.getStatus() != null, Employee::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增员工信息
     *
     * @param bo 员工信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(EmployeeBo bo) {
        Employee add = MapstructUtils.convert(bo, Employee.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改员工信息
     *
     * @param bo 员工信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(EmployeeBo bo) {
        Employee update = MapstructUtils.convert(bo, Employee.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Employee entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除员工信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 注册公司账号添加信息到员工表
     *
     * @param user 注册信息
     * @return
     */
    @Override
    public Employee insertByRegisterCompany(SysUserBo user) {
        Employee employee = new Employee();
        employee.setId(user.getUserId());
        employee.setUserName(user.getUserName());
        employee.setPhone(user.getPhonenumber());
        employee.setPassword(user.getClearPassword());
        employee.setRealName(StrUtil.isNotBlank(user.getRealName()) ? user.getRealName() : "主账号");
        employee.setRole(GeneralEnum.ADMIN);
        employee.setStatus(GeneralEnum.Y);
        boolean b = baseMapper.insert(employee) > 0;
        if (!b) {
            throw new ServiceException("注册公司账号时添加员工表错误！");
        }
        return employee;
    }

    /**
     * 注册员工账号添加信息到员工表
     *
     * @param user 注册信息
     * @return
     */
    @Override
    public Employee insertByRegisterEmployee(SysUserBo user) {
        Employee employee = new Employee();
        employee.setId(user.getUserId());
        employee.setCompanyId(user.getCompanyId());
        employee.setUserName(user.getUserName());
        employee.setPhone(user.getPhonenumber());
        employee.setPassword(user.getClearPassword());
        employee.setRealName(user.getRealName());
        employee.setRole(GeneralEnum.EMPLOYEE);
        employee.setStatus(GeneralEnum.Y);
        boolean b = baseMapper.insert(employee) > 0;
        if (!b) {
            throw new ServiceException("注册员工账号时添加员工表错误！");
        }
        return employee;
    }

    /**
     * 后台审核公司的注册账号
     *
     * @param userId 审核的用户ID
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean auditRegister(Long userId) {
        // 查询审核的记录
        Employee employeeDB = baseMapper.selectById(userId);
        if (BeanUtil.isEmpty(employeeDB)) {
            throw new ServiceException("未找到该条用户信息！");
        }

        // 获取数据库原本账号状态
        GeneralEnum status = employeeDB.getStatus();
        log.info("原本账号状态：{}", status);

        // 修改SysUser表的状态
        sysUserService.updateUserStatusByAudit(userId, status);

        Employee employee = new Employee();
        employee.setId(userId);
        employee.setStatus(GeneralEnum.Y.equals(status) ? GeneralEnum.N : GeneralEnum.Y);
        return baseMapper.updateById(employee) > 0;
    }

    /**
     * 补全公司信息后员工关联主体
     *
     * @param userId    用户ID
     * @param companyId 公司主体ID
     * @return
     */
    @Override
    public Boolean updateByCompanyId(Long userId, Long companyId) {
        boolean result = baseMapper.update(null,
            new LambdaUpdateWrapper<Employee>()
                .set(Employee::getCompanyId, companyId)
                .eq(Employee::getId, userId)) > 0;
        if (!result) {
            throw new ServiceException("员工补全主体信息时关联主体ID错误！");
        }
        return Boolean.TRUE;
    }

    /**
     * 修改密码
     *
     * @param userPasswordBo 修改密码信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int resetUserPwd(UserPasswordBo userPasswordBo) {
        int i = userService.resetUserPwd(userPasswordBo.getUserId(), userPasswordBo.getEncryptPassword());
        if (i > 0) {
            return baseMapper.update(null,
                new LambdaUpdateWrapper<Employee>()
                    .set(Employee::getPassword, userPasswordBo.getNewPassword())
                    .eq(Employee::getId, userPasswordBo.getUserId()));
        }
        return i;
    }

    /**
     * 根据员工id查询所属主体公司ID
     *
     * @param userId 员工ID
     * @return 主体公司ID
     */
    @Override
    public Long queryCompanyIdByUserId(Long userId) {
        Employee employee = baseMapper.selectById(userId);
        if (BeanUtil.isEmpty(employee)) {
            throw new ServiceException("未找到该员工信息！");
        }
        if (employee.getCompanyId() == null) {
            throw new ServiceException("该员工未关联主体公司！");
        }
        return employee.getCompanyId();
    }
}
